<template>
  <div class="address-manager">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <button class="back-btn" @click="goBack">
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z" fill="currentColor"/>
        </svg>
      </button>
      <h1 class="page-title">地址管理</h1>
      <button class="add-btn" @click="openAddForm">
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" fill="currentColor"/>
        </svg>
      </button>
    </header>

    <!-- 主要内容区 -->
    <main class="address-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>加载地址中...</p>
      </div>

      <!-- 空状态 -->
      <div v-else-if="addresses.length === 0" class="empty-state">
        <div class="empty-icon">📍</div>
        <h3>暂无地址信息</h3>
        <p>点击右上角按钮添加新地址</p>
        <button class="primary-btn" @click="openAddForm">添加地址</button>
      </div>

      <!-- 地址列表 -->
      <div v-else class="address-list">
        <div v-for="address in addresses" :key="address.id" class="address-card">
          <div class="card-header">
            <span class="recipient">{{ address.recipient }}</span>
            <span class="phone">{{ formatPhone(address.phone) }}</span>
            <span v-if="address.isDefault === 1" class="default-tag">默认地址</span>
          </div>
          <p class="address-detail">
            {{ address.province }} {{ address.city }} {{ address.addrDetail }}
            <span v-if="address.isDefault === 0" class="non-default-tag">（非默认地址）</span>
          </p>
        </div>
      </div>
    </main>

    <!-- 地址表单弹窗 -->
    <div v-if="showForm" class="form-modal">
      <div class="modal-overlay" @click="closeForm"></div>
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ formTitle }}</h2>
          <button class="close-btn" @click="closeForm">&times;</button>
        </div>
        
        <form @submit.prevent="submitForm" class="address-form">
          <div class="form-group">
            <label>收件人</label>
            <input 
              v-model="formData.recipient" 
              type="text" 
              placeholder="请输入收件人姓名"
              required
            >
          </div>
          
          <div class="form-group">
            <label>联系电话</label>
            <input 
              v-model="formData.phone" 
              type="tel" 
              placeholder="请输入手机号码"
              pattern="^1[3-9]\d{9}$"
              required
            >
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>省份</label>
              <select v-model="formData.province" @change="loadCities" required>
                <option value="">请选择省份</option>
                <option v-for="(cities, province) in provinces" :key="province" :value="province">{{ province }}</option>
              </select>
            </div>
            
            <div class="form-group">
              <label>城市</label>
              <select v-model="formData.city" :disabled="!formData.province" required>
                <option value="">请选择城市</option>
                <option v-for="city in filteredCities" :key="city" :value="city">{{ city }}</option>
              </select>
            </div>
          </div>
          
          <div class="form-group">
            <label>详细地址</label>
            <textarea 
              v-model="formData.addrDetail" 
              placeholder="街道、小区、门牌号等"
              rows="3"
              required
            ></textarea>
          </div>
          
          <div class="form-actions">
            <button type="button" class="secondary-btn" @click="closeForm">取消</button>
            <button type="submit" class="primary-btn">保存地址</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { get, post } from '../util/Request'
import addressData from '../../pca.json' // 导入 JSON 数据

export default {
  setup() {
    const router = useRouter()
    const loading = ref(true)
    const addresses = ref([])
    const showForm = ref(false)
    const isEditing = ref(false)
    const currentAddressId = ref(null)
    
    // 表单数据
    const formData = ref({
      recipient: '',
      phone: '',
      province: '',
      city: '',
      addrDetail: '',
      isDefault: false
    })
    
    // 省市区数据
    const provinces = ref(addressData) // 使用 JSON 数据
    const filteredCities = ref([]) // 存储当前省份的城市
    
    // 方法
    const loadCities = () => {
      // 确保城市数据正确加载
      const selectedProvince = formData.value.province;
      filteredCities.value = selectedProvince ? Object.keys(provinces.value[selectedProvince]) : [];
    }
    
    const formatPhone = (phone) => {
      return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3')
    }
    
    const loadAddresses = () => {
      loading.value = true; // 设置加载状态
      const uid = sessionStorage.getItem('uid');
      if (uid) {
        get(`addresses/${uid}`).then((res) => {
          if (res.data.code === 200) {
            addresses.value = res.data.data;
          } else {
            console.error("加载地址失败:", res.data.message);
          }
          loading.value = false; // 结束加载状态
        }).catch(error => {
          console.error("请求错误:", error);
          loading.value = false; // 结束加载状态
        });
      } else {
        console.error("未找到 uid");
        loading.value = false; // 结束加载状态
      }
    }
    
    const openAddForm = () => {
      isEditing.value = false
      currentAddressId.value = null
      formData.value = {
        recipient: '',
        phone: '',
        province: '',
        city: '',
        addrDetail: '',
        isDefault: false
      }
      showForm.value = true
    }
    
    const closeForm = () => {
      showForm.value = false
    }
    
    const submitForm = async () => {
      try {
        const uid = sessionStorage.getItem('uid')
        const addressData = { ...formData.value, uid }
        addressData.isDefault = addressData.isDefault ? 1 : 0; // 转换为 1 或 0
        
        let res
        if (isEditing.value) {
          res = await put(`/addresses/new/${currentAddressId.value}`, addressData)
        } else {
          res = await post('/addresses/new', addressData)
        }
        
        if (res.data.code === 200) {
          await loadAddresses()
          closeForm()
        }
      } catch (error) {
        console.error('保存地址失败:', error)
      }
    }
    
    const goBack = () => {
      router.go(-1)
    }
    
    // 生命周期
    onMounted(() => {
      loadAddresses()
    })
    
    return {
      loading,
      addresses,
      showForm,
      formData,
      provinces,
      filteredCities,
      formatPhone,
      openAddForm,
      closeForm,
      submitForm,
      goBack,
      loadCities // 返回 loadCities 方法
    }
  }
}
</script>

<style scoped>
.address-manager {
  max-width: 600px;
  margin: 0 auto;
  background-color: #f8f9fa;
  min-height: 100vh;
}

/* 顶部导航栏 */
.app-header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.back-btn, .add-btn {
  background: none;
  border: none;
  color: #333;
  cursor: pointer;
  padding: 8px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

/* 主要内容区 */
.address-content {
  padding: 16px;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #4285f4;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #4285f4;
}

.empty-state h3 {
  margin: 0 0 8px;
  color: #333;
}

.empty-state p {
  margin: 0 0 24px;
  color: #666;
}

/* 地址列表 */
.address-list {
  display: grid;
  gap: 12px;
}

.address-card {
  position: relative;
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}

.address-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.recipient {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.phone {
  margin-left: 12px;
  color: #666;
  font-size: 14px;
}

.default-tag {
  margin-left: 8px;
  padding: 2px 6px;
  background-color: #e3f2fd;
  color: #1976d2;
  border-radius: 4px;
  font-size: 12px;
}

.non-default-tag {
  margin-left: 8px;
  padding: 2px 6px;
  background-color: #f8d7da; /* 非默认地址的背景色 */
  color: #721c24; /* 非默认地址的文字颜色 */
  border-radius: 4px;
  font-size: 12px;
}

.address-detail {
  margin: 0;
  color: #666;
  line-height: 1.5;
}

/* 表单弹窗 */
.form-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  border-bottom: 1px solid #eee;
}

.modal-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #666;
  cursor: pointer;
}

.address-form {
  padding: 16px;
  overflow-y: auto;
  max-height: calc(90vh - 60px);
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #0a0101;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 90%;
  padding: 10px;
  border: 1px solid #7b7171;
  border-radius: 18px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  border-color: #4285f4;
  outline: none;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

/* 按钮样式 */
.primary-btn {
  padding: 12px 24px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.primary-btn:hover {
  background-color: #3367d6;
}

.secondary-btn {
  padding: 12px 24px;
  background-color: #f1f3f4;
  color: #333;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.secondary-btn:hover {
  background-color: #e0e0e0;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .address-card {
    padding: 12px;
  }
}
</style>